package cn.com.dhcc.turbo.service.monitor.handler;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import cn.com.dhcc.app.core.AppEnv.ParaGetTool;
import cn.com.dhcc.app.core.CM;
import cn.com.dhcc.app.core.service.Log;
import cn.com.dhcc.app.core.service.Log.LOGTYPE;
import cn.com.dhcc.app.core.util.CollectionUtil;
import cn.com.dhcc.app.core.util.FreemarkerUtil;
import cn.com.dhcc.turbo.entity.monitor.Quota;
import cn.com.dhcc.turbo.entity.monitor.QuotaValueOnTime;
import cn.com.dhcc.turbo.entity.registry.NodeInfo;
import cn.com.dhcc.turbo.service.monitor.AlertVo;
import cn.com.dhcc.turbo.service.monitor.MonitorQuotaStatic.ALERT_PIPELINE;
import cn.com.dhcc.turbo.service.monitor.MonitorQuotaStatic.QUOTA_OWNER;
import cn.com.dhcc.turbo.service.monitor.MonitorService;
import cn.com.dhcc.turbo.service.monitor.MonitorVO;
import cn.com.dhcc.turbo.service.registry.AdapterInfoService;
import cn.com.dhcc.turbo.service.registry.NodeInfoService;
@Service("EMAILHANDLER")
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)//不能是单利
public class EmailHandler implements QuotaOntimeValueHandler{

	@Autowired
	MonitorService monitorService;
	@Autowired
	NodeInfoService nodeInfoService;
	@Autowired
	AdapterInfoService adapterInfoService;
	
	@SuppressWarnings("deprecation")
	Logger logger = Log.getExistLogger(LOGTYPE.TURBO);
	public List<QuotaValueOnTime> toHandlerRos = new ArrayList<QuotaValueOnTime>();

	@Override
	public void registRows(QuotaValueOnTime valueOnTime) {
		toHandlerRos.add(valueOnTime);
	}

	@Override
	public void handler() {
		
		try {
			if(CollectionUtil.hasElement(toHandlerRos)){
				logger.info("开始进行自动告警处理...");
				
				/*
				如果是本地节点管理员应该处理的告警，就发一份邮件给管理员，邮件内容包含所有指标。
				如果是系统管理员应该处理的告警，就将告警邮件发给具体的系统,并且发给系统所属节点管理员，和本地节点管理员
				*/
				Map<String,MonitorVO> emailToNode = new HashMap<String, MonitorVO>();
				Map<String,MonitorVO>  emailToSys = new HashMap<String, MonitorVO>();
				//本地节点：所有信息都会发给本地节点管理员
				NodeInfo localNode = nodeInfoService.getLocalNode();
				emailToNode.put(localNode.getId(), new MonitorVO());
				
				for (Iterator<QuotaValueOnTime> iterator = toHandlerRos.iterator(); iterator.hasNext();) {
					QuotaValueOnTime quotaValueOnTime = iterator.next();
					Quota quota = monitorService.getQuotaByQuotaCode(quotaValueOnTime.getQuotaCode());
					String owner = quota.getOwner();
					AlertVo alertVo = new AlertVo();
					alertVo.setOnTimeValueId(quotaValueOnTime.getId());
					alertVo.setAlertMsg(quotaValueOnTime.getAlertMsg());
					alertVo.setQuotaName(quota.getName());
					alertVo.setCtime(quotaValueOnTime.getMtime());
					String ownerId = quotaValueOnTime.getOwnerId();
					
					NodeInfo nodeInfo = null;//
				   // AdapterInfo adapterInfo = null;//
					if(emailToNode.get(ownerId)==null){//
						if(QUOTA_OWNER.ADAPTER.getCode().equalsIgnoreCase(owner)){
							/*nodeInfo = nodeInfoService.getNodeInfoBySysId(ownerId);
							adapterInfo = adapterInfoService.get(ownerId);
							MonitorVO monitorVoSys = new MonitorVO();
							monitorVoSys.setEmailAdress(adapterInfo.getAdminEmail());
							monitorVoSys.setQuickHandlerUrl(nodeInfo.getInstallUrl());
							emailToSys.put(ownerId, monitorVoSys);*/
						}else{
							nodeInfo = nodeInfoService.get(ownerId);
							MonitorVO monitorVoNode = new MonitorVO();
							monitorVoNode.setEmailAdress(nodeInfo.getAdminEmail());
							monitorVoNode.setQuickHandlerUrl(nodeInfo.getInstallUrl());
							emailToNode.put(ownerId, monitorVoNode);
						}
					}
					if(QUOTA_OWNER.ADAPTER.getCode().equalsIgnoreCase(owner)){//如果属于系统给系统管理员发
						//alertVo.setOwnerStr(nodeInfo.getNodeName()+"-"+sysInfo.getName());
						//emailToSys.get(ownerId).getAlertVos().add(alertVo);
					}else{
						alertVo.setOwnerStr(nodeInfo.getNodeName());
						emailToNode.get(ownerId).getAlertVos().add(alertVo);
					}
					
					//有告警都需要给本地节点按管理员发
					MonitorVO monitorVoLocalNode = emailToNode.get(localNode.getId());
					monitorVoLocalNode.setEmailAdress(localNode.getAdminEmail());
					monitorVoLocalNode.setQuickHandlerUrl(localNode.getInstallUrl());
					emailToNode.get(localNode.getId()).getAlertVos().add(alertVo);
					//修改指标最后告警处理时间
					monitorService.updateLastAlertTime(quota, new Date());
				}
				
				sendAlertEmailToAdmin(emailToNode.values(),emailToSys.values());
			}
		} catch (Exception e) {
			logger.error("告警自动处理异常",e);
		}
	}
	public static String ALERT_EMAIL_TO_NODE_ADMIN = "";
	public static String ALERT_EMAIL_TO_SYS_ADMIN = "";
	public static final String MONITOR_EMAIL_TITLE = ParaGetTool.getPara("monitor.email.title");
	private void sendAlertEmailToAdmin(Collection<MonitorVO> toNode,Collection<MonitorVO> toSys) {
		if(!StringUtils.hasText(ALERT_EMAIL_TO_NODE_ADMIN)||
				!StringUtils.hasText(ALERT_EMAIL_TO_SYS_ADMIN)){
			ALERT_EMAIL_TO_NODE_ADMIN = this.getClass().getResource("/template/monitor/alert_email_to_node_admin.flt").getFile();
			ALERT_EMAIL_TO_SYS_ADMIN = this.getClass().getResource("/template/monitor/alert_email_to_sys_admin.flt").getFile();
		}
		logger.info("开始进行自动告警处理-发送告警邮件!");
		if(CollectionUtil.hasElement(toNode)){
			for (Iterator<MonitorVO> iterator = toNode.iterator(); iterator
					.hasNext();) {
				MonitorVO monitorVO = iterator.next();
				sendAlertEmail(monitorVO, true);
			}
		}
		if(CollectionUtil.hasElement(toSys)){
			for (Iterator<MonitorVO> iterator = toSys.iterator(); iterator
					.hasNext();) {
				MonitorVO monitorVO = iterator.next();
				sendAlertEmail(monitorVO, false);
			}
				
		}
	}
   private void sendAlertEmail(MonitorVO monitorVO,boolean toNode){
		if(monitorVO.getAlertVos().size()!=0){
			String emailToName = monitorVO.getAlertVos().get(0).getOwnerStr();
			Map<String, Object> rootMap = new HashMap<String, Object>();
			rootMap.put("alert", monitorVO);
			try {
				String emailContent = FreemarkerUtil.flushData(toNode?ALERT_EMAIL_TO_NODE_ADMIN:ALERT_EMAIL_TO_SYS_ADMIN, rootMap);
				logger.info("开始发告警邮件给["+emailToName+"]，邮件地址["+monitorVO.getEmailAdress()+"]，内容:"+emailContent);
				CM.getMailService().sendHtmlEmail(monitorVO.getEmailAdress(), MONITOR_EMAIL_TITLE, emailContent, null, null);
			} catch (Exception e) {
				logger.error("发告警邮件给["+emailToName+"]，邮件地址["+monitorVO.getEmailAdress()+"]失败",e);
				return;
			}
			//发成功后，添加已处理过的告警方法
			for (Iterator<AlertVo> iterator2 = monitorVO.getAlertVos().iterator(); iterator2
					.hasNext();) {
				AlertVo alertVo =  iterator2.next();
				String onTimeValueId = alertVo.getOnTimeValueId();
				try {
					QuotaValueOnTime onTime = monitorService.getQuotaValueOnTimeByQuotaId(onTimeValueId);
					if(onTime!=null){
						String hasUsedMethod = onTime.getHasAlertMethod();
						String method = ALERT_PIPELINE.EMAIL.getCode();
						onTime.setHasAlertMethod(StringUtils.hasText(hasUsedMethod)?onTime.getHasAlertMethod()+","+method:method);
						CM.getDao().updateModuleById("修改告警实时值以使用过的通道", onTime, null);
					}
				} catch (Exception e) {
					logger.error("修改告警实时值以使用过的通道出错",e);
					return;
				}
			}
		}
   }
   
}
